import { Injectable } from '@angular/core';
import { Action, NgxsAfterBootstrap, State, StateContext } from '@ngxs/store';
import { ProjectAction } from './project.action';
import { HttpClient } from '@angular/common/http';

export interface ProjectStateModel {
  modal: any;
}

@State<ProjectStateModel>({
  name: 'project',
  defaults: {
    modal: {},
  },
})
@Injectable({
  providedIn: 'root',
})
export class ProjectState implements NgxsAfterBootstrap {

  constructor(private http: HttpClient) {
  }

  ngxsAfterBootstrap(ctx: StateContext<any>): void {
    if (!ctx.getState().messages) ctx.patchState({messages: {}});
  }

  @Action(ProjectAction.SaveModal)
  SaveModal(ctx: StateContext<ProjectStateModel>) {
    if (ctx.getState().modal.status !== 'VALID') return;
    let model = ctx.getState().modal.model;
    return this.http.post(`/api/deploy`, model);
  }
}
